package com.ruoyi.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 条形码工具
 *
 * @author fish dream
 */
public class BarCodeUtils {

    public static String barCodeImageBase64(String data) {
        return barCodeImageBase64(data, 300, 100);
    }

    public static String barCodeImageBase64(String data, int width, int height) {
        Map<EncodeHintType, Object> hints = new HashMap<>(2);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        ByteArrayOutputStream stream = null;
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.CODE_128, width, height, hints);
            stream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "jpeg", stream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        byte[] bytes = Base64.encodeBase64(stream.toByteArray());
        String base64 = new String(bytes);
        return "data:image/jpeg;base64," + base64;
    }
}
